import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/storage.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/utils/storage_util.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/api/auth_apis.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/user_login_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class LoginController extends GetxController {
  /// [lastPressedAt] 退出的倒计时
  DateTime? lastPressedAt;

  /// [textEditingControllerUserName] 用户名
  TextEditingController textEditingControllerUserName = TextEditingController();

  /// [textEditingControllerPassword] 密码
  TextEditingController textEditingControllerPassword = TextEditingController();

  /// [userNameNode] 用户名焦点
  FocusNode userNameNode = FocusNode();

  /// [passwordNode] 密码焦点
  FocusNode passwordNode = FocusNode();

  final userNameHasFocus = false.obs;

  final passwordHasFocus = false.obs;

  /// 保存的账号密码
  List<UserLoginEntity> userList = UserManager.getLoginCredentialList();

  RxBool isClick = false.obs;

  final rememberPwd = (StorageUtil.getBool(StorageConstants.rememberLoginCredential) ?? false).obs;

  @override
  void onInit() {
    super.onInit();
    if (rememberPwd.value && userList.isNotEmpty) {
      textEditingControllerUserName.text = userList.first.userName;
      textEditingControllerPassword.text = userList.first.passWord;
    }
    userNameNode.addListener(_focusUserNameListener);
    passwordNode.addListener(_focusPassWordListener);
  }

  @override
  void onReady() {
    super.onReady();
    if (UserManager.isLoggedIn) {
      goHome();
    }
  }

  @override
  void dispose() {
    textEditingControllerUserName.dispose();
    textEditingControllerPassword.dispose();
    userNameNode.removeListener(_focusUserNameListener);
    passwordNode.removeListener(_focusPassWordListener);
    super.dispose();
  }

  void _focusUserNameListener() {
    userNameHasFocus.value = userNameNode.hasFocus;
  }

  void _focusPassWordListener() {
    passwordHasFocus.value = passwordNode.hasFocus;
  }

  /// 登录
  void loginDo() async {
    /// executeAutoDispose: 页面关闭，自动销毁请求
    // AppLoadingDialog.show();
    if (textEditingControllerUserName.value.text.isEmpty) {
      AppToast.showError('请输入工号/电话号');
      return;
    }
    if (textEditingControllerPassword.value.text.isEmpty) {
      AppToast.showError('请输入密码');
      return;
    }
    isClick.value = true;
    final result = await AuthApis.login(
      username: textEditingControllerUserName.value.text,
      password: textEditingControllerPassword.value.text,
    ).execute();

    result.onSuccess((result) {
      /// 保存token
      if (result.data != null) {
        UserManager.saveUser(result.data!);
        UserManager.saveToken('${result.data!.tokenType} ${result.data!.accessToken}');
        if (rememberPwd.value) {
          UserManager.saveLoginCredential(
            textEditingControllerUserName.value.text,
            textEditingControllerPassword.value.text,
          );
        }
        goHome();
      } else {
        AppToast.showError('用户数据为空');
        // goHome();
      }
    });

    result.onError((result) {
      isClick.value = false;
    });
  }

  /// 重置账号
  void reset() async {
    textEditingControllerUserName.clear();
    textEditingControllerPassword.clear();
  }

  void onRememberPwdChanged(bool? value) {
    value ??= false;
    rememberPwd.value = value;
    StorageUtil.setBool(StorageConstants.rememberLoginCredential, value);
  }

  /// 登录完跳转
  void goHome() {
    // SmartDialog.showLoading(
    //   msg: '登录中',
    // );
    Future.delayed(const Duration(milliseconds: 1000)).then((value) {
      // SmartDialog.dismiss();
      Get.offNamed(AppRoutes.home);
      // isClick.value = false;
      AppToast.showSuccess('登录成功');
    });
  }

  /// 判断是否退出页面
  bool isPopPage() {
    if (lastPressedAt == null || DateTime.now().difference(lastPressedAt!) > const Duration(seconds: 1)) {
      return false;
    } else {
      return true;
    }
  }

  /// 移除历史账号
  void removeHistoryUser(UserLoginEntity user) {
    UserManager.removeLoginCredential(user.userName);
    userList = UserManager.getLoginCredentialList();
    Get.back();
    update();
  }

  /// 选择历史账号
  void selectHistoryUser(UserLoginEntity user) {
    textEditingControllerUserName.text = user.userName;
    textEditingControllerPassword.text = user.passWord;
  }
}
